package com.twosnail.frame.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.twosnail.frame.commin.exception.BuziException;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * Created by Administrator on 2017/7/11/011.
 */
@SuppressWarnings("serial")
public class CouponUseLog extends Model<CouponUseLog> {
    public static final CouponUseLog me = new CouponUseLog() ;

    /**
     * 获取登录用户下所有健身劵使用记录
     */
    public Page<Record> getCouponUseLogs(HttpSession session , int pageNumber, int pageSize){
        long userId =  Long.parseLong(session.getAttribute("userId").toString());
        StringBuffer sb = new StringBuffer(" from coupon_use_log a left join sys_user b on a.userId = b.id where a.status = 3 ");
            sb.append( " and a.userId = "+userId) ;
        return Db.paginate(pageNumber, pageSize,
                "select a.orderCode,a.checkCode,FROM_UNIXTIME(a.useTime/1000, '%Y-%m-%d %H:%i:%S')useTime ,b.neckName  " , sb.toString() );
    }

    /**
     * 获取登录用户下所有健身劵使用记录
     */
    public List<Record> getListById(HttpSession session ){
        long userId =  Long.parseLong(session.getAttribute("userId").toString());
        return Db.find("select a.orderCode,a.checkCode,FROM_UNIXTIME(a.useTime/1000, '%Y-%m-%d %H:%i:%S')useTime ,b.neckName from coupon_use_log a left join sys_user b on a.userId = b.id where a.status = 3 and a.userId = "+userId);
    }

    /**
     * 获取指定用户下所有健身劵使用记录
     */
    public List<Record> getListById(long userId ){
        return Db.find("select a.orderCode,a.checkCode,FROM_UNIXTIME(a.useTime/1000, '%Y-%m-%d %H:%i:%S')useTime ,b.neckName from coupon_use_log a left join sys_user b on a.userId = b.id where a.status = 3 and a.userId = "+userId);
    }

    /**
     * 获取所有健身劵使用记录
     */
    public List<Record> getListByGymId(long gymId){
        return Db.find("SELECT a.orderCode, a.checkCode, FROM_UNIXTIME( a.useTime / 1000, '%Y-%m-%d %H:%i:%S' ) useTime, b.neckName FROM coupon_use_log a LEFT JOIN sys_user b ON a.userId = b.id LEFT JOIN coupon c ON a.couponId = c.couponId LEFT JOIN gym d ON c.gymId = d.gymId WHERE a. STATUS = 3 AND d.gymId = "+gymId+" ORDER BY userId");
    }

    /**
     * 获取登录用户下健身劵使用已使用个数
     * @param session
     */
    public long getUse( HttpSession session ){
        long userId = Long.parseLong(session.getAttribute("userId").toString());
        return Db.queryLong("SELECT COUNT(1) FROM coupon_use_log a where a.status = 3 and a.userId = ? " , userId );
    }

    /**
     * 获取总个数
     * @param session
     */
    public long getAll( HttpSession session ){
        long userId = Long.parseLong(session.getAttribute("userId").toString());
        Long gymId = SysUser.me.getUserById(userId ).getLong("gymId");
        return Db.queryLong("SELECT COUNT(1) FROM coupon_use_log a left join coupon b on a.couponId = b.couponId " +
                "left join gym c on b.gymId = c.gymId where  a.status = 3 and c.gymId = ?" , gymId );
    }

    /**
     * 获取单个健身劵使用记录
     * @param checkCode
     * @param session
     * @return
     */
    public CouponUseLog getByCheckCode( String checkCode, HttpSession session){
        long gymId = SysUser.me.getUserById(  Long.parseLong(session.getAttribute("userId").toString()) ).getLong("gymId");
        return me.findFirst( "select a.* from coupon_use_log a left join coupon b on a.couponId = b.couponId " +
                "left join gym c on b.gymId = c.gymId where a.`status` = 2 and a.checkCode = ?  and c.gymId = ?" , checkCode,gymId ) ;
    }

    /**
     * 修改健身劵信息
     * @param couponUseLog
     * @throws BuziException
     */
    public void updateUseLog( CouponUseLog couponUseLog ,HttpSession session) throws BuziException{
        couponUseLog.set("status",3);
        couponUseLog.set("useTime",System.currentTimeMillis());
        couponUseLog.set("userId",session.getAttribute("userId"));
        if( !couponUseLog.update() ) {
            throw new BuziException( "验证失败，系统错误!" );
        }
    }

    /**
     * 获取登录用户下所有健身劵使用记录
     */
    public Page<Record> getUseLogById(long userId , int pageNumber, int pageSize){
        StringBuffer sb = new StringBuffer(" from coupon_use_log a left join sys_user b on a.userId = b.id where a.status = 3 ");
        sb.append( " and a.userId = "+userId) ;
        return Db.paginate(pageNumber, pageSize,
                "select a.orderCode,a.checkCode,FROM_UNIXTIME(a.useTime/1000, '%Y-%m-%d %H:%i:%S')useTime ,b.neckName  " , sb.toString() );
    }

    /**
     * 过期健身劵数量 返还团购次数
     */
    public void updateUseLogCounts(){
        Db.update("UPDATE gym g SET g.counts = g.counts + ( SELECT count(1) FROM coupon_use_log a LEFT JOIN coupon b ON a.couponId = b.couponId WHERE a. STATUS = 2 AND b.gymId = g.gymId )");
    }

    /**
     * 退款
     */
    public void refund(){
        // 未使用的健身卷
        long time = System.currentTimeMillis();
        WxUserAccoutLog log;
        List<CouponUseLog> list = me.find("SELECT * FROM coupon_use_log WHERE STATUS = 2");
        if( list != null && list.size() > 0 ){
            for( CouponUseLog couponUseLog : list ){
                // 设置健身卷无效
                couponUseLog.set("status",4);
                couponUseLog.set("refundTime",time);
                couponUseLog.update();
                log = new WxUserAccoutLog();
                log.set("createTime",time);
                log.set("wxUserId",couponUseLog.getLong("wxUserId"));
                if( couponUseLog.getLong("xdCouponId") != null && couponUseLog.getLong("xdCouponId") > 0 ){ //代金劵购买的健身卷
                    log.set("type",6);
                    // 回复代金劵
                    XdCoupon.me.updateState(couponUseLog.getLong("xdCouponId"));
                }else{// 现金购买健身劵
                    log.set("type",5);
                    log.set("accout",couponUseLog.getBigDecimal("cast"));
                    // 更新钱包余额
                    WxUser.me.updateAccount(couponUseLog.getLong("wxUserId"),couponUseLog.getBigDecimal("cast"));
                }
                log.save();
            }
        }
    }

}
